<?php
/* 
	This file is Copyright Matthew Wilkinson 2009.
	
	This file is part of Oxygen.

	Oxygen is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License version 3 as published by
	the Free Software Foundation at http://www.gnu.org/licenses/gpl-3.0.html

	Oxygen is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

*/
	
	Final Class Database
		{
		
		private static $driver = null;
		private static $allowedcallers = Array('Security', 'Database', 'Log', 'Settings', 'Data', 'User', 'Theme');
		
		private static $driverstr = null;
		private static $connstring = null;
		
		public static function set($driver, $connstring)
			{
			if (self::$driverstr === null AND self::$connstring === null)
				{
				self::$driverstr = $driver;
				self::$connstring = $connstring;
				}
			}
		
		private static $constructed = FALSE;
		private static function _construct()
			{
			if (self::$constructed)
				{
				return;
				}
			else
				{
				self::$constructed = TRUE;
				}
			
			if (self::$driverstr === null AND self::$connstring === null)
				{
				throw new RuntimeException('database/no_config_strings');
				}
			else
				{
				self::$driver = new self::$driverstr(self::$connstring);
				}
			
			
			}

		public static function query($query)
			{
			self::_construct();
			if (array_search(Security::Caller(), self::$allowedcallers) === FALSE)
				{
				Log::Warning('database/direct_query');
				}
			if (!is_string($query))
				{
				throw new InvalidArgumentException('database/query_not_string');
				}
			if (func_num_args() == 1)
				{
				return self::$driver->query($query);
				}
			else
				{
				$args = func_get_args();
				$query = array_shift($args);
				foreach($args as $arg)
					{
					$start = strpos($query, '{');					
					$end = strpos($query, '}');
					$type = substr($query, $start + 1, $end-$start-1);
					switch($type)
						{
						case 'int';
							$arg = Security::integer($arg);
						break;
						
						case 'string';
							$arg = Security::string($arg);
						break;
						
						case 'url';
							$arg = Security::url($arg);
						break;
						
						case 'text';
						default;
							$arg = Security::text($arg);
						break;
						}
					$query = preg_replace('/{' . $type . '}/', $arg, $query, 1);
					}
				return self::query($query);
				}
			}
			
		public static function inserted_id()
			{
			return self::$driver->inserted_id();
			}
		
		public static function affected_rows()
			{
			return self::$driver->affected_rows();
			}
		
		}

?>